import { AnyAction } from 'redux'
import * as TYPES from '../action-types'
import { validate, register, login } from '../../api/user'
import { RegisterPayload, RegisterResult, LoginPayload, LoginResult } from '@/typings/user'
import { push } from 'connected-react-router'
import { message } from 'antd'
export default {
    validate(): AnyAction {
        return {
            type: TYPES.VALIDATE,
            payload: validate()
        }
    },
    register(values: RegisterPayload) {
        return (dispatch: any) => {
            (async function () {
                try {
                    let result: RegisterResult = await register<RegisterResult>(values)
                    if (result.success) {
                        dispatch(push('/login'))
                    } else {
                        message.error(result.message)
                    }
                } catch (error) {
                    message.error('注册失败')
                }
            })()
        }
    },
    login(values: LoginPayload) {
        return (dispatch: any) => {
            (async function () {
                try {
                    let result: LoginResult = await login<LoginResult>(values)
                    if (result.success) {
                        sessionStorage.setItem('access_token', result.data.token)
                        dispatch(push('/profile'))
                    } else {
                        message.error(result.message)
                    }
                } catch (error) {
                    message.error('登录失败')
                }
            })()
        }
    },
    logout() {
        return (dispatch: any) => {
            sessionStorage.removeItem('access_token')
            dispatch({ type: TYPES.LOGOUT })
            dispatch(push('/login'))
        }
    },
    changeAvatar(avatar: string) {
        return {
            type: TYPES.CHANGE_AVATAR,
            payload: avatar
        }
    }
}